/*
* Copyright (c) 2025 Huawei Device Co., Ltd.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including but not limited to the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to provide persons with access to the Software
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGE OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

<template>
  <div class='game' ref='gameContainer'>
    <!-- 按钮组 -->
    <div class='button-group' :style='{
      marginTop: `${topMargin + 8}px`,
      marginLeft: `${(topMargin ? 0 : margins.leftTopMargin) + 16}px`,
      marginRight: `${(topMargin ? 0 : margins.rightTopMargin) + 16}px`
    }'>
      <!-- 顶部按钮 -->
      <div class='top-buttons' :style="{ width: !needChangeView ? '100%' : 'auto' }">
        <img :src='topButtons[0]' class='button-image'>
        <!-- 中间空白填充 -->
        <div v-if='needChangeView' class='center-blank'></div>
        <img v-if='rowNum > 6 && !needChangeView' src='../assets/stars.png' alt='' :style="{ height: '54px' }" />
        <img :src='topButtons[1]' class='button-image'>
      </div>

      <!-- 中间空白填充 -->
      <div v-if='needChangeView' class='center-blank'></div>

      <!-- 侧边按钮 -->
      <div v-if='needChangeView' class='bottom-buttons'>
        <img :src='bottomButtons[0]' class='button-image'>
        <img :src='bottomButtons[1]' class='button-image'>
        <img :src='bottomButtons[2]' class='button-image'>
      </div>
    </div>

    <!-- 中间网格容器 -->
    <div class='grid-container' :style="{
      paddingLeft: needChangeView ? `${margins.leftBottomMargin || margins.leftCenterMargin + 16}px` : `${margins.leftCenterMargin + 16}px`,
      paddingRight: needChangeView ? `${margins.rightBottomMargin || margins.rightCenterMargin + 16}px` : `${margins.rightCenterMargin + 16}px`,
      gridTemplateColumns: `repeat(${rowNum}, minmax(68px, 72px))`,
      gridAutoRows: 'minmax(68px, 72px)'
    }">
      <div v-for='(item, index) in gridItems' :key='index' class='grid-item'>
        <img :src='item' class='grid-image'>
      </div>
    </div>

    <!-- 底部按钮 -->
    <div v-if='!needChangeView' class='bottom-buttons' :style='{
      marginLeft: `${(bottomMargin ? 0 : margins.leftBottomMargin) + 16}px`,
      marginRight: `${(bottomMargin ? 0 : margins.rightBottomMargin) + 16}px`,
      marginBottom: `${bottomMargin + 12}px`
    }'>
      <img :src='bottomButtons[0]' class='button-image'>
      <div class='bottomRight-buttons'>
        <img :src='bottomButtons[1]' class='button-image'>
        <img :src='bottomButtons[2]' class='button-image'>
      </div>
    </div>
  </div>
</template>

<script lang='ts'>
import Vue from 'vue';
import { topButtons, gridImages, bottomButtons } from '../common/ResPath';
import { AreaUtils } from '../utils/AreaUtils';
import { AvoidAreaType } from '../common/windowCommon';

const TAG = 'GAMEPAGE:';

export default Vue.extend({
  name: 'GameView',
  data() {
    return {
      topButtons,
      gridImages,
      bottomButtons,
      needChangeView: false,
      margins: {
        leftTopMargin: 0,
        rightTopMargin: 0,
        leftBottomMargin: 0,
        rightBottomMargin: 0,
        leftCenterMargin: 0,
        rightCenterMargin: 0
      },
      rowNum: 4,
      columnNum: 8,
      gridItems: gridImages,
      topMargin: AreaUtils.getInstance().getTopMargin(),
      bottomMargin: AreaUtils.getInstance().getBottomMargin()
    };
  },
  methods: {
    reCulcAvoidArea() {
      AreaUtils.getAvoidAreaLocation().then((res) => {
        AreaUtils.getInstance().setAvoidValue(res.areaLocation, res.marginValue);
        this.margins = AreaUtils.getAllMargin();
        this.needChangeView = AreaUtils.checkIfNeedChangeView();
      });
    },
    calculateGridItemNum() {
      const game = this.$refs.gameContainer as Element;
      if (game) {
        const itemSize = 72; // 每个 grid-item 的大小
        const margin = 6; // 每个 grid-item 的外边距
        const topHeight = 76;
        const bottomHeight = 63;
        const sideWidth = 4;

        //计算容器宽高
        const gridWidth = Number(getComputedStyle(game).getPropertyValue('width').replace('px', ''));
        const gridHeight = Number(getComputedStyle(game).getPropertyValue('height').replace('px', ''));

        //计算左右边距和容器可用高度
        let leftMargin;
        let rightMargin;
        let availableHeight = gridHeight - topHeight;
        if (this.needChangeView) {
          leftMargin = this.margins.leftBottomMargin || this.margins.leftCenterMargin + sideWidth;
          rightMargin = this.margins.rightBottomMargin || this.margins.rightCenterMargin + sideWidth;
          availableHeight -= bottomHeight;
        } else {
          leftMargin = this.margins.leftCenterMargin + sideWidth;
          rightMargin = this.margins.rightCenterMargin + sideWidth;
        }

        //计算网格数量
        this.rowNum = Math.floor((gridWidth - leftMargin - rightMargin) / (itemSize + 2 * margin));
        this.columnNum = Math.round(availableHeight / (itemSize + 2 * margin));
        let totalNum = this.rowNum * this.columnNum;
        const randomItems = [];
        for (let i = 0; i < totalNum; i++) {
          const randomIndex = Math.floor(Math.random() * gridImages.length);
          randomItems.push(gridImages[randomIndex]);
        }
        this.gridItems = randomItems;
      }
    },
    handleStatusBarChange(event: any) {
      console.debug(TAG, `statusBarChange data is ${JSON.stringify(event.detail)}`);
      const data = event.detail;
      const areaType = data.type;
      this.reCulcAvoidArea();
      if (areaType === AvoidAreaType.TYPE_SYSTEM) {
        this.topMargin = AreaUtils.px2vp(data.area.topRect.height);
        AreaUtils.getInstance().setTopMargin(this.topMargin);
      }
      if (areaType === AvoidAreaType.TYPE_CUTOUT) {
        this.calculateGridItemNum();
      }
      if (areaType === AvoidAreaType.TYPE_NAVIGATION_INDICATOR) {
        this.bottomMargin = AreaUtils.px2vp(data.area.bottomRect.height);
        AreaUtils.getInstance().setBottomMargin(this.bottomMargin);
      }
    }
  },
  mounted() {
    this.reCulcAvoidArea();
    this.calculateGridItemNum();
    window.addEventListener('resize', this.calculateGridItemNum);
    window.addEventListener('statusBarChange', this.handleStatusBarChange);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.reCulcAvoidArea);
    window.removeEventListener('statusBarChange', this.handleStatusBarChange);
  }
});
</script>

<style scoped>
.game {
  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  background-image: url('../assets/game_background.png');
  background-size: auto 100%;
  background-position: left;
  background-attachment: fixed;
}

.top-buttons {
  display: flex;
  height: 76px;
  gap: 20px;
  justify-content: space-between;
}

.bottom-buttons {
  display: flex;
  height: 63px;
  gap: 20px;
  justify-content: space-between;
}

.button-image {
  object-fit: auto;
  height: 100%;
}

.center-blank {
  width: 100%;
  height: 100%;
}

.button-group {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.grid-container {
  display: grid;
  gap: 12px;
  overflow-y: auto;
  scrollbar-width: 0;
  justify-content: center;
  margin-bottom: 15px;
  margin-top: 15px;
}

.grid-item {
  width: 100%;
  aspect-ratio: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background-image: url('../assets/bird_bg.svg');
  background-size: contain;
  background-position: center;
}

.grid-image {
  width: 100%;
  height: 55px;
  object-fit: Contain;
}

.bottomRight-buttons {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  gap: 20px;
}

/* 横屏适配 */
@media (orientation: landscape) {
  .button-group {
    display: flex;
    justify-content: space-between;
    flex-direction: row;
  }
}
</style>
